import {
  addUserUsingPost,
  updateUserByIdUsingPost,
} from '@/services/student-management-system/yonghumokuai';
import { Form, Input, message, Radio } from 'antd';
import { forwardRef, useEffect, useImperativeHandle } from 'react';

interface UpdateUserProps {
  editUserVO?: API.UpdateUserDTO;
  onCloseModal?: () => void;
}

export interface UpdateUserMethods {
  submitForm: () => Promise<boolean>;
}

export const UpdateUser = forwardRef<UpdateUserMethods, UpdateUserProps>((props, ref) => {
  const { editUserVO, onCloseModal } = props;
  const [form] = Form.useForm();

  const submitForm = async () => {
    // 获取表单提交数据
    const values = await form.validateFields();
    const res = editUserVO?.id
      ? await updateUserByIdUsingPost({ ...values, id: editUserVO.id })
      : await addUserUsingPost(values);

    if (res.code === 200) {
      message.success('操作成功');
      onCloseModal?.();
      return true;
    } else {
      message.error('操作失败：' + res.msg);
      return false;
    }
  };

  useEffect(() => {
    if (editUserVO) {
      form.setFieldsValue({
        realName: editUserVO.realName,
        phone: editUserVO.phone,
        role: editUserVO.role,
        status: editUserVO.status,
      });
    }
  }, [editUserVO, form]);

  useImperativeHandle(ref, () => ({ submitForm }));

  return (
    <Form form={form} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} autoComplete="off">
      {!editUserVO?.id && (
        <Form.Item label="用户名" name="username" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
      )}

      <Form.Item label="姓名" name="realName" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item label="手机号" name="phone" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item label="角色" name="role" rules={[{ required: true }]}>
        <Radio.Group>
          <Radio value={0}>学生</Radio>
          <Radio value={1}>教师</Radio>
          <Radio value={2}>管理员</Radio>
        </Radio.Group>
      </Form.Item>

      <Form.Item label="状态" name="status" rules={[{ required: true }]}>
        <Radio.Group>
          <Radio value={1}>启用</Radio>
          <Radio value={0}>禁用</Radio>
        </Radio.Group>
      </Form.Item>
    </Form>
  );
});
